package com.macro.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.exception.ApiException;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.dao.OmsOrderItemDao;
import com.macro.mall.dao.OmsOrderReturnApplyDao;
import com.macro.mall.dto.OmsOrderReturnApplyResult;
import com.macro.mall.dto.OmsReturnApplyQueryParam;
import com.macro.mall.dto.UmsAdminDTO;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.service.OmsOrderReturnApplyService;
import com.macro.mall.service.OmsOrderService;
import com.macro.mall.service.UmsAdminService;
import com.macro.mall.service.UmsMemberService;
import com.macro.mall.wx.domain.WxRefundDTO;
import com.macro.mall.wx.service.RefundService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单退货管理Service
 */
@Service
public class OmsOrderReturnApplyServiceImpl implements OmsOrderReturnApplyService {
    Logger logger = LoggerFactory.getLogger(OmsOrderReturnApplyServiceImpl.class);
    @Value("${redis.key.orderId}")
    private String REDIS_KEY_ORDER_ID;
    @Value("${redis.database}")
    private String REDIS_DATABASE;
    @Autowired
    private OmsOrderReturnApplyDao returnApplyDao;
    @Autowired
    private OmsOrderReturnApplyMapper returnApplyMapper;
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private UmsIntegrationChangeHistoryMapper uichMapper;
    @Autowired
    private PmsProductMapper pmsProductMapper;
    @Autowired
    private UmsMemberMapper umsMemberMapper;
    @Autowired
    private SmsCouponHistoryMapper couponHistoryMapper;
    @Autowired
    private OmsDistributionOrderMapper odoMapper;
    @Autowired
    private OmsDistributionStoreOrderMapper odsoMapper;
    @Autowired
    private OmsOrderSettingMapper oosMapper;
    @Autowired
    private RefundService refundService;
    @Autowired
    private PmsStockMapper pmsStockMapper;
    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;
    @Autowired
    private UmsMemberReceiveAddressMapper receiveAddressMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UmsStoreMapper storeMapper;
    @Autowired
    private OmsOrderService omsOrderService;
    @Autowired
    private PmsCombinedProductMapper pmsCombinedProductMapper;
    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private SmsCouponMapper couponMapper;
    @Autowired
    private OmsOrderItemDao omsOrderItemDao;
    @Override
    public CommonPage<OmsOrderReturnApply> list(UmsAdmin admin,OmsReturnApplyQueryParam queryParam, Integer pageSize, Integer pageNum) {
        UmsStoreExample example = new UmsStoreExample();
        example.createCriteria().andUserIdEqualTo(admin.getId());
        List<UmsStore> umsStores = this.storeMapper.selectByExample(example);
        List<OmsOrderReturnApply> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(umsStores)){
            PageHelper.startPage(pageNum, pageSize);
            list = returnApplyDao.getList(umsStores.get(0).getId(),queryParam);
        }
        return CommonPage.restPage(list);
    }

    @Override
    public int delete(List<Long> ids) {
        OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
        example.createCriteria().andIdIn(ids).andReturnStatusEqualTo(3);
        return returnApplyMapper.deleteByExample(example);
    }

    @Override
    public CommonResult confirm(String currentUserName,Long id) {

        //查询售后单信息
        OmsOrderReturnApply orderReturnApply = returnApplyMapper.selectByPrimaryKey(id);
        //查询总订单表信息
        OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderReturnApply.getOrderId());
        //查询用户
        UmsMember umsMember = umsMemberMapper.selectByPrimaryKey(omsOrder.getMemberId());
        //查询子订单
        OmsOrderItem omsOrderItem = orderItemMapper.selectByPrimaryKey(orderReturnApply.getOrderItemId());
        //查询商品
        PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(omsOrderItem.getProductId());
        //获取售后单申请类型
        Integer orderType = orderReturnApply.getOrderType();
        //设置售后单状态
        orderReturnApply.setReturnStatus(2);
        orderReturnApply.setHandleTime(new Date());
        orderReturnApply.setHandleMan(currentUserName);
        this.returnApplyMapper.updateByPrimaryKeySelective(orderReturnApply);
        if (orderType.equals(1)) {
            //处理退货退款确认收货逻辑
            //修改子订单状态
            omsOrderItem.setStatus(4);
            this.orderItemMapper.updateByPrimaryKeySelective(omsOrderItem);
            //计算修改订单状态
            Integer status = this.getStatus(omsOrder, omsOrder.getStatus());
            omsOrder.setStatus(status);
            BigDecimal payAmount = omsOrder.getPayAmount();
            omsOrder.setPayAmount(payAmount.subtract(orderReturnApply.getReturnAmount()));
            this.orderMapper.updateByPrimaryKeySelective(omsOrder);
            //回滚库存
            this.returnStock(currentUserName, omsOrder, orderReturnApply);
            //返还积分
            this.returnCalIntegration(omsOrder, omsOrderItem.getGiftIntegration(), umsMember);
            logger.info("走过了返还积分-------------------");
            //返还优惠券
            this.returnSmsCouponHistory(omsOrder, status);
            //返还经纪人佣金
            this.returnOmsDistributionOrder(omsOrder, omsOrderItem);
            //返还店铺提现佣金
            this.returnOmsDistributionStoreOrder(omsOrder, omsOrderItem);
            //微信退款
            try {
                this.returnMoney(omsOrder, orderReturnApply);
            } catch (ApiException e) {
                e.printStackTrace();
                return CommonResult.success(e.getMessage());
            }catch (Exception e){
                e.printStackTrace();
            }
        } else if(orderType.equals(2)){
            //处理换货逻辑
            //回滚库存
            this.returnStock(currentUserName, omsOrder, orderReturnApply);
            //创建一个新的销售订单
            this.returnOrder(omsOrder,orderReturnApply,omsOrderItem);
        }
        return CommonResult.success("审核成功");
    }

    /**
     * 创建换货发货订单
     * @author zhouboyu
     * @Date 2020年9月24日
     * @param omsOrder
     * @param orderReturnApply
     * @param omsOrderItem
     */
    public void returnOrder(OmsOrder omsOrder, OmsOrderReturnApply orderReturnApply,OmsOrderItem omsOrderItem) {
        OmsOrder newOrder = new OmsOrder();
        UmsMemberReceiveAddress umsMemberReceiveAddress = this.receiveAddressMapper.selectByPrimaryKey(orderReturnApply.getCompanyAddressId());
        BeanUtils.copyProperties(omsOrder,newOrder);
        newOrder.setCouponId(null);
        newOrder.setOrderSn(this.generateOrderSn(newOrder));
        newOrder.setCreateTime(new Date());
        newOrder.setTotalAmount(orderReturnApply.getReturnAmount());
        newOrder.setPayAmount(BigDecimal.ZERO);
        newOrder.setFreightAmount(BigDecimal.ZERO);
        newOrder.setPromotionAmount(BigDecimal.ZERO);
        newOrder.setIntegrationAmount(BigDecimal.ZERO);
        newOrder.setCouponAmount(BigDecimal.ZERO);
        newOrder.setDiscountAmount(BigDecimal.ZERO);
        newOrder.setStatus(1);//代发货
        newOrder.setOrderType(4);//换货发货
        newOrder.setIntegration(0);
        newOrder.setPromotionInfo(null);
        newOrder.setReceiverPostCode(umsMemberReceiveAddress.getPostCode());
        newOrder.setReceiverName(umsMemberReceiveAddress.getName());
        newOrder.setReceiverPhone(umsMemberReceiveAddress.getPhoneNumber());
        newOrder.setReceiverProvince(umsMemberReceiveAddress.getProvince());
        newOrder.setReceiverCity(umsMemberReceiveAddress.getCity());
        newOrder.setReceiverRegion(umsMemberReceiveAddress.getRegion());
        newOrder.setConfirmStatus(0);
        newOrder.setDeleteStatus(0);
        newOrder.setPaymentTime(new Date());
        newOrder.setDeliveryTime(null);
        newOrder.setReceiveTime(null);
        newOrder.setCommentTime(null);
        newOrder.setModifyTime(null);
        newOrder.setSendType(0);
        newOrder.setAgentSendType(0);
        newOrder.setId(null);
        this.orderMapper.insertSelective(newOrder);
        OmsOrderItem newOrderItem = new OmsOrderItem();
        BeanUtils.copyProperties(omsOrderItem,newOrderItem);
        newOrderItem.setOrderId(newOrder.getId());
        newOrderItem.setOrderSn(newOrder.getOrderSn());
        newOrderItem.setProductQuantity(orderReturnApply.getProductCount());
        newOrderItem.setPromotionName(null);
        newOrderItem.setPromotionAmount(BigDecimal.ZERO);
        newOrderItem.setCouponAmount(BigDecimal.ZERO);
        newOrderItem.setIntegrationAmount(BigDecimal.ZERO);
        newOrderItem.setGiftGrowth(0);
        newOrderItem.setCommissionAmount(BigDecimal.ZERO);
        newOrderItem.setStatus(1);
        newOrderItem.setId(null);
        //如果换的是等价的，改子订单规格
        if(orderReturnApply.getReplaceSkuId() != null && !orderReturnApply.getReplaceSkuId().equals(orderReturnApply.getOriginSkuId())){
            newOrderItem.setProductSkuId(orderReturnApply.getReplaceSkuId());
        }
        this.orderItemMapper.insertSelective(newOrderItem);
        PmsSkuStock pmsSkuStock = this.pmsSkuStockMapper.selectByPrimaryKey(newOrderItem.getProductSkuId());
        newOrderItem.setProductSn(pmsSkuStock.getSkuCode());
        newOrderItem.setProductAttr(pmsSkuStock.getSpData());
        pmsSkuStock.setLockStock((pmsSkuStock.getLockStock()+newOrderItem.getProductQuantity()));
        this.pmsSkuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     * @author zhouboyu
     * @Date 2020年9月24日
     */
    private String generateOrderSn(OmsOrder order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = REDIS_DATABASE+":"+ REDIS_KEY_ORDER_ID + date;
        Long increment = redisService.incr(key, 1);
        sb.append(date);
        sb.append(String.format("%02d", order.getSourceType()));
        sb.append(String.format("%02d", order.getPayType()));
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }
    /**
     * 微信退款
     * @author zhouboyu
     * @Date 2020年9月24日
     * @param omsOrder
     * @param orderReturnApply
     */
    public void returnMoney(OmsOrder omsOrder, OmsOrderReturnApply orderReturnApply) throws Exception{
        logger.info("微信退款价格---------------------"+orderReturnApply.getProductRealPrice());
        logger.info("微信退款数量---------------------"+orderReturnApply.getProductCount());
        //调用微信退款接口
        WxRefundDTO wxRefundDTO = new WxRefundDTO(orderReturnApply.getOrderSn(), orderReturnApply.getOrderItemId().toString());
        //获取订单总金额，设置保留两位小数，并且四舍五入
        //订单总金额-会员优惠-优惠券优惠-积分优惠-管理员设置的优惠
        BigDecimal omsOrderMoney = (omsOrder.getTotalAmount().subtract(omsOrder.getPromotionAmount())
        .subtract(omsOrder.getCouponAmount().subtract(omsOrder.getIntegrationAmount().subtract(omsOrder.getDiscountAmount())))
        ).multiply(BigDecimal.TEN).multiply(BigDecimal.TEN);
        wxRefundDTO.setTotal_fee(String.valueOf(omsOrderMoney.intValue()));
        //获取退款金额，并设置
        int i  = orderReturnApply.getProductRealPrice().multiply(new BigDecimal(orderReturnApply.getProductCount())).multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).intValue();
        logger.info("获取退款金额，并设置---------------------"+i);
        wxRefundDTO.setRefund_fee(String.valueOf(i));
        this.refundService.refund(wxRefundDTO);
    }

    /**
     * 回滚库存
     * @author zhouboyu
     * @Date 2020年9月24日
     * @param omsOrder
     * @return
     */
    public void returnStock(String currentUserName, OmsOrder omsOrder,OmsOrderReturnApply orderReturnApply){
        Long agentId = null;
        if (omsOrder.getAgentSendType().equals(1)) {
            agentId = omsOrder.getAgentId();
        }
        //先判断是普通商品还是组合商品
        if (omsOrder.getOrderType().equals(1)) {
            //组合商品回滚库存
            PmsCombinedProductExample combinedProductExample = new PmsCombinedProductExample();
            combinedProductExample.createCriteria().andParentIdEqualTo(orderReturnApply.getOriginSkuId());
            List<PmsCombinedProduct> pmsCombinedProducts = pmsCombinedProductMapper.selectByExample(combinedProductExample);
            for (PmsCombinedProduct pmsCombinedProduct : pmsCombinedProducts){
                returnStock(currentUserName, agentId,pmsCombinedProduct.getSkuStockId(),orderReturnApply.getProductCount()*pmsCombinedProduct.getNum());
            }
        }else {
            returnStock(currentUserName, agentId,orderReturnApply.getOriginSkuId(),orderReturnApply.getProductCount());
        }
    }

    /**
     *
     * @param agentId 经纪人id
     * @param skuId 规格id
     * @param num 回滚数量
     */
    private void returnStock(String currentUserName, Long agentId, Long skuId,Integer num){
        UmsAdminDTO admin = adminService.getAdminDTOByUserName(currentUserName);
        PmsSkuStock pmsSkuStock = this.pmsSkuStockMapper.selectByPrimaryKey(skuId);
        pmsSkuStock.setStock((num+pmsSkuStock.getStock()));
        this.pmsSkuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
        PmsStockExample example = new PmsStockExample();
        PmsStockExample.Criteria criteria = example.createCriteria().andSkuStockIdEqualTo(skuId);
        if(agentId!=null){
            criteria.andAgentIdEqualTo(agentId);
        }else{
            criteria.andAgentIdIsNull();
        }
        List<PmsStock> pmsStockList = this.pmsStockMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(pmsStockList)){
            PmsStock pmsStock = pmsStockList.get(0);
            pmsStock.setStock(num+pmsStock.getStock());
            this.pmsStockMapper.updateByPrimaryKeySelective(pmsStock);
        }else{
            //说明该子商品不是经纪人发货，但退货退款会加到经纪人上
            PmsStock pmsStock = new PmsStock();
            pmsStock.setSkuStockId(skuId);
            pmsStock.setStock(num);
            pmsStock.setAgentId(agentId);
            pmsStock.setMemberId(admin.getId());
            pmsStock.setMemberUserName(admin.getUserName());
            pmsStock.setStoreId(admin.getStoreId());
            this.pmsStockMapper.insert(pmsStock);
        }
    }
    /**
     * 返还店铺提现金额
     * @author zhouboyu
     * @Date 2020年9月24日
     * @param omsOrder
     * @return
     */
    public void returnOmsDistributionStoreOrder(OmsOrder omsOrder,OmsOrderItem omsOrderItem){
        //查询平台提成
        OmsOrderSettingExample oosExample = new OmsOrderSettingExample();
        oosExample.createCriteria().andPlatformCommissionIsNotNull();
        List<OmsOrderSetting> omsOrderSettings = oosMapper.selectByExample(oosExample);
        OmsOrderSetting omsOrderSetting = omsOrderSettings.get(0);
        //查询分销店铺提现订单
        OmsDistributionStoreOrderExample odsoExample = new OmsDistributionStoreOrderExample();
        odsoExample.createCriteria().andOrderIdEqualTo(omsOrder.getId());
        List<OmsDistributionStoreOrder> odsOrders = odsoMapper.selectByExample(odsoExample);
        if(omsOrderSetting!=null&&!CollectionUtils.isEmpty(odsOrders)){
            BigDecimal amount = new BigDecimal(100-omsOrderSetting.getPlatformCommission())
                    .multiply(omsOrderItem.getRealAmount())
                    .multiply(new BigDecimal(omsOrderItem.getProductQuantity()))
                    .divide((BigDecimal.TEN.multiply(BigDecimal.TEN)),2,BigDecimal.ROUND_HALF_UP);
            OmsDistributionStoreOrder omsDistributionStoreOrder = odsOrders.get(0);
            omsDistributionStoreOrder.setAmount(omsDistributionStoreOrder.getAmount().subtract(amount));
            this.odsoMapper.updateByPrimaryKeySelective(omsDistributionStoreOrder);
        }
    }

    /**
     * 返还分销员佣金
     * @author zhouboyu
     * @Date 2020年9月24日
     * @param omsOrder
     * @return
     */
    public void returnOmsDistributionOrder(OmsOrder omsOrder,OmsOrderItem omsOrderItem){
        OmsDistributionOrderExample odoExample = new OmsDistributionOrderExample();
        odoExample.createCriteria().andOrderIdEqualTo(omsOrder.getId())
                .andStoreIdEqualTo(omsOrder.getUserStoreId());
        List<OmsDistributionOrder> odOrders = odoMapper.selectByExample(odoExample);
        if(!CollectionUtils.isEmpty(odOrders)){
            OmsDistributionOrder omsDistributionOrder = odOrders.get(0);
            omsDistributionOrder.setCommissionAmount(omsDistributionOrder.getCommissionAmount().subtract(omsOrderItem.getCommissionAmount()));
            this.odoMapper.updateByPrimaryKeySelective(omsDistributionOrder);
        }
    }

    /**
     * 返还优惠券
     * @author zhouboyu
     * @Date 2020年9月24日
     * @param omsOrder
     * @param status
     *          订单状态为关闭状态才可以返还优惠券
     * @return
     */
    public  void returnSmsCouponHistory(OmsOrder omsOrder,Integer status){
        if(omsOrder.getCouponId()!=null){
            if(status.equals(4)){
                SmsCouponHistoryExample example = new SmsCouponHistoryExample();
                example.createCriteria().andCouponIdEqualTo(omsOrder.getCouponId()).andOrderSnEqualTo(omsOrder.getOrderSn()).andMemberIdEqualTo(omsOrder.getMemberId());
                List<SmsCouponHistory> smsCouponHistories = couponHistoryMapper.selectByExample(example);
                if (!CollectionUtils.isEmpty(smsCouponHistories)) {
                    SmsCouponHistory smsCouponHistory = smsCouponHistories.get(0);
                    smsCouponHistory.setUseStatus(0);
                    smsCouponHistory.setUseTime(null);
                    smsCouponHistory.setOrderSn(null);
                    couponHistoryMapper.updateByPrimaryKeySelective(smsCouponHistory);
                    SmsCoupon smsCoupon = couponMapper.selectByPrimaryKey(omsOrder.getCouponId());
                    smsCoupon.setUseCount(smsCoupon.getUseCount()-1);
                    this.couponMapper.updateByPrimaryKey(smsCoupon);
                    omsOrder.setCouponId(null);
                    this.orderMapper.updateByPrimaryKeySelective(omsOrder);
                }
            }
        }
    }
    /**
     * 退还积分
     * @author zhouboyu
     * @Date 2020年9月24日
     * @param omsOrder
     * @param integration 子订单中的积分，下单时候就是商品积分*买的数量
     * @return
     */
    public  Integer returnCalIntegration(OmsOrder omsOrder,Integer integration,UmsMember umsMember){
        logger.info("退还积分方法进没进来-----------------");
        UmsIntegrationChangeHistory integrationHistory = new UmsIntegrationChangeHistory();
        ////设置退货商品积分操作记录
        integrationHistory.setMemberId(omsOrder.getMemberId());
        integrationHistory.setCreateTime(new Date());
        //设置积分来源是购物
        integrationHistory.setSourceType(3);
        //设置积分改变类型为减少
        integrationHistory.setChangeType(1);
        //设置操作人员和操作备注
        integrationHistory.setStoreId(umsMember.getStoreId());
        integrationHistory.setMemberUserId(umsMember.getId());
        integrationHistory.setMemberUserName(umsMember.getUsername());
        integrationHistory.setChangeCount(integration);
        integrationHistory.setOperateMan(umsMember.getUsername());
        integrationHistory.setOperateNote("退还积分");
        logger.info("积分变动数据-----------------"+integrationHistory.toString());
        this.uichMapper.insertSelective(integrationHistory);
        umsMember.setIntegration(umsMember.getIntegration()-integration);
        this.umsMemberMapper.updateByPrimaryKeySelective(umsMember);
        return integration;
    }
    @Override
    public OmsOrderReturnApplyResult getItem(Long id) {
        return returnApplyDao.getDetail(id);
    }
    @Override
    public CommonResult agree(OmsOrderReturnApply returnApply) {
        //查询售后单信息
        OmsOrderReturnApply orderReturnApply = returnApplyMapper.selectByPrimaryKey(returnApply.getId());
        if(orderReturnApply.getReturnStatus().equals(0)){
            //查询总订单表信息
            OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderReturnApply.getOrderId());
            OmsOrderItem omsOrderItem = this.orderItemMapper.selectByPrimaryKey(orderReturnApply.getOrderItemId());
            if(StringUtils.isBlank(returnApply.getReason())){//卖家同意
                if(orderReturnApply.getOrderType().equals(0)){//仅退款
                    orderReturnApply.setReturnStatus(2);
                    orderReturnApply.setHandleTime(new Date());
                    this.returnApplyMapper.updateByPrimaryKeySelective(orderReturnApply);
                    omsOrderItem.setStatus(4);//子订单关闭
                    this.orderItemMapper.updateByPrimaryStatus(omsOrderItem);
                    omsOrder.setStatus(this.getStatus(omsOrder,omsOrder.getStatus()));
                    //仅退款订单，把实付金额再计算，高强10.28加
                    BigDecimal payAmount = omsOrder.getPayAmount();
                    omsOrder.setPayAmount(payAmount.subtract(orderReturnApply.getReturnAmount()));
                    this.orderMapper.updateByPrimaryKeySelective(omsOrder);
                    //返回积分
                    UmsMember umsMember = umsMemberMapper.selectByPrimaryKey(omsOrder.getMemberId());
                    this.returnCalIntegration(omsOrder,omsOrderItem.getGiftIntegration(),umsMember);
                    //返还优惠券
                    this.returnSmsCouponHistory(omsOrder, omsOrderItem.getStatus());
                    //回滚库存,没发货，锁库存减回去
                    List<OmsOrderItem> list = new ArrayList<>();
                    list.add(omsOrderItem);
                    omsOrderService.releaseSkuStockLock(list);
                    try {
                        this.returnMoney(omsOrder, orderReturnApply);
                    } catch (ApiException e) {
                        e.printStackTrace();
                        throw e;
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    orderReturnApply.setReturnStatus(1);
                    orderReturnApply.setHandleTime(new Date());
                    this.returnApplyMapper.updateByPrimaryKeySelective(orderReturnApply);
                }
                //修改销量，换货不修改
                if (!orderReturnApply.getOrderType().equals(2)) {
                    List<OmsOrderItem> list = new ArrayList<>();
                    list.add(omsOrderItem);
                    omsOrderItemDao.upDateSale(list);
                }
            }else{//卖家拒绝
                orderReturnApply.setReturnReason(returnApply.getReason());
                orderReturnApply.setReturnStatus(3);
                orderReturnApply.setHandleTime(new Date());
                this.returnApplyMapper.updateByPrimaryKeySelective(orderReturnApply);
                omsOrderItem.setStatus(orderReturnApply.getOrderItemStatus());
                this.orderItemMapper.updateByPrimaryStatus(omsOrderItem);
                omsOrder.setStatus(this.getStatus(omsOrder,omsOrder.getStatus()));
                this.orderMapper.updateByPrimaryKeySelective(omsOrder);
            }
        }else{
            return CommonResult.failed("该订单状态不是待处理");
        }
        return CommonResult.success(returnApply);
    }

    /**
     * 计算订单status
     * @param omsOrder
     * @param status
     * @return
     */
    private Integer getStatus(OmsOrder omsOrder,Integer status){
        int flag = 0;
        //查询订单下所有退货商品信息
        OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
        orderItemExample.createCriteria().andOrderIdEqualTo(omsOrder.getId());
        List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(orderItemExample);
        for (OmsOrderItem orderItem:omsOrderItems ) {
            if(orderItem.getStatus().equals(4)){
                flag++;
            }
        }
        if(flag==omsOrderItems.size()){
            status = 4;
        }
        return status;
    }
}
